import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:cave_flutter/config/whl_base_controller.dart';
import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/model/user_model.dart';
import 'package:cave_flutter/model/whl_user_info_model.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/utils/whl_current_limiting_util.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';

import '../../common/chat_manager.dart';
import '../../routes/whl_app_pages.dart';

class WhlChatLogic extends WhlBaseController {
  // List<String> tabList = ['聊天', '灵魂羁绊', 'Cave', '通讯录'];
  List<String> tabList = ['聊天', 'Cave', '通讯录'];
  int selectedIndex = 0;
  PageController pageController = PageController(initialPage: 0);
  List<WhlUserInfoModel> followedList = [];
  List<NIMSession> conversationList = [];
  List<NIMSession> caveList = [];
  List<NIMSession> allList = [];
  int page = 1;
  int limit = 9999;
  MessageService messageService = NimCore.instance.messageService;

  StreamSubscription? sectionUpdateSubscription;

  EasyRefreshController refreshController1 = EasyRefreshController(controlFinishRefresh: true, controlFinishLoad: true);
  EasyRefreshController refreshController2 = EasyRefreshController(controlFinishRefresh: true, controlFinishLoad: true);

  List<UserModel> friendList = [];

  Map<String, UserModel> userInfoData = {};

  Map<String, dynamic> caveInfoData = {};

  @override
  onInit() {
    super.onInit();
    onGetFollowedList();
    onGetConversationList();
    addMessageListener();
    // onGetFriendList();
    // messageService.createSession(sessionId: sessionId, sessionType: sessionType, time: time)
  }

  @override
  void onClose() {
    super.onClose();
    sectionUpdateSubscription?.cancel();
  }

  addMessageListener() {
    sectionUpdateSubscription = messageService.onSessionUpdate.listen((event) {
      print("receive 111");
      bool hasNew = false;
      event.forEach((element) {
        bool isNew = respAndCheckSession(element);
        if (isNew) {
          hasNew = isNew;
        }
      });
      if (hasNew) {
        getAllUserInfo();
      } else {
        update();
      }
      // conversationList = event;
    });
  }

  getAllUserInfo() async {
    List allIds = conversationList.map((e) => e.sessionId).toList();
    if (allIds.isEmpty) {
      return;
    }
    WhlApi.batchReplaceUserInfo.post(allIds).then((value) {
      if (value.isSuccess()) {
        List data = value.data ?? [];
        List<UserModel> models = data.map((e) => UserModel.fromJson(e)).toList();
        for (var element in models) {
          userInfoData[element.acid ?? ""] = element;
        }
        update();
      }
    });
  }

  getAllCaveInfo() {
    List allTids = caveList.map((e) => e.sessionId).toList();
    if (allTids.isEmpty) {
      return;
    }
    WhlApi.batchCaveInfo.post(allTids).then((value) {
      if (value.isSuccess()) {
        List data = value.data ?? [];
        print('cave列表-------------------');
        print(data);

        for (var element in data) {
          if (element['tid'] != null) {
            caveInfoData[element['tid']] = element;
          }
        }
        update();
      }
    });
  }

  onGetConversationList() async {
    NIMResult<List<NIMSession>> result =
        await messageService.querySessionList(limit);

    allList = result.data ?? [];
    conversationList = [];
    caveList = [];
    for (var element in allList) {
      if (element.sessionType == NIMSessionType.p2p) {
        conversationList.add(element);
      }

      if (element.sessionType == NIMSessionType.team) {
        caveList.add(element);
      }
    }
    print('聊天列表-------------------');
    print(conversationList.length);
    refreshController1.finishRefresh(IndicatorResult.success);
    getAllUserInfo();
    getAllCaveInfo();
    // update();
  }

  onGetFollowedList() async {}

  bool respAndCheckSession(NIMSession session) {
    NIMSession? oldSession;
    for (var e in conversationList) {
      if (e.sessionId == session.sessionId) {
        oldSession = e;
        break;
      }
    }
    if (oldSession != null) {
      conversationList.remove(oldSession);
      conversationList.insert(0, session);
      return false;
    } else {
      conversationList.insert(0, session);
      return true;
    }
  }

  chatRefresh() {
    onGetConversationList();
  }

  onPageChanged(index, {bool isClick = false}) {
    selectedIndex = index;
    if (isClick) {
      pageController.jumpToPage(index);
    }
    update();
    if (index == 1) {
      WhlCurrentLimitingUtil.debounce(() {
        onGetFollowedList();
      });
    } else if (index == 3) {
      // WhlCurrentLimitingUtil.debounce(() {
      //   onGetFriendList();
      // });
    } else {
      WhlCurrentLimitingUtil.debounce(() {
        onGetConversationList();
      });
      // doClickVoiceRecord () {
      // WhlPermissionUtil.reqMicrophonePermission(onSuccessAction: () {
      //   Get.bottomSheet(WhlRecordSheetPage(), isScrollControlled: false);
      // });
      // }
    }
  }

  String? onGetLastMessageContent(NIMSession session) {
    NIMMessageType? messageType = session.lastMessageType;
    String? lastMessageContent = session.lastMessageContent;
    Map<String, dynamic> a = session.lastMessageAttachment?.toMap() ?? {};
    if ((lastMessageContent ?? "").isEmpty) {
      return '';
    }
    if (messageType == NIMMessageType.text) {
      return lastMessageContent ?? "";
    } else if (messageType == NIMMessageType.audio) {
      return '[语音]';
    } else if (messageType == NIMMessageType.image) {
      return '[图片]';
    } else if (messageType == NIMMessageType.file) {
      return '[文件]';
    } else if (messageType == NIMMessageType.custom) {
      int customType = a["customType"] ?? 0;
      if (customType == MyCustomMsgType.videoCall.tag) {
        return '[视频通话]';
      } else if (customType == MyCustomMsgType.audioCall.tag) {
        return '[语音通话]';
      }
      // print("custom type ${lastMessageContent}");
      // if (lastMessageContent == "1" ||lastMessageContent == "-1") {
      //   return '[通话]';
      // }else if (lastMessageContent == "2" ||lastMessageContent == "-2") {
      //   return '[语音通话]';
      // }
    } else {
      return '';
    }
  }

  doClickConversation(NIMSession session) {
    Get.toNamed(Routes.roomPage,
        arguments: {'showName': 'showName', "toAccountId": session.sessionId, "userModel": userInfoData[session.sessionId]})?.then((value) {
      update();
    });
  }

  doClickCave(Map cave) {
    Get.toNamed(Routes.caveGroupChat, arguments: {
      'id': cave['id'],
      'tid': cave['tid'],
      'type': cave['caveType'],
      'caveName': cave['caveName'],
      'showName': 'showName',
    });
  }

  doClickDeleteConversation(NIMSession conversation) {
    // WhlRCIMUtils.engine.removeConversation(conversation.conversationType ?? RCIMIWConversationType.private, conversation.targetId ?? '', null,
    //     callback: IRCIMIWRemoveConversationCallback(onConversationRemoved: (int? code) {
    //   conversationList.remove(conversation);
    //   update();
    // }));
  }

  doClickDeleteConversationFromUserId(String userId) {
    // RCIMIWConversation? conversation = conversationList.firstWhereOrNull((element) => element.targetId == userId);
    // if (conversation == null) return;
    // WhlRCIMUtils.engine.removeConversation(conversation.conversationType ?? RCIMIWConversationType.private, conversation.targetId ?? '', null,
    //     callback: IRCIMIWRemoveConversationCallback(onConversationRemoved: (int? code) {
    //   conversationList.remove(conversation);
    //   update();
    // }));
  }

  doClickFollow(WhlUserInfoModel model) async {
    Map<String, dynamic> params = {
      'followUserId': model.id,
    };
    BotToast.showLoading();
    // await WhlApi.removeFriend.post(params);
    BotToast.closeAllLoading();
    followedList.remove(model);
    update();
  }

  bool onCheckIsCustomerService(String userId) {
    return userId == WHLGlobalConfig.userServiceAccountId;
  }
}
